var request = require('request');
var md5 = require('MD5');
var dateFormat = require('dateformat');
var express = require('express');
var router = express.Router();

var SID = 'e917b54301f860160772d22a42a2077a';
var TOKEN = 'e87dbcd806d368412948548314ce02c6';
var APPID = 'b2f655aedb9649f7afc40bccb498a7fc';
var SMS_REST = 'http://www.ucpaas.com/maap/sms/code';
var SMS_ID = '7492';
var selectFields = '-password -token';

var createPassword = function(password) {
	return Util.mixPassword(password, 'employer');
};

/* 获取 */
router.get('/', function (req, res, next) {
	var limit = req.query.limit;
	var skip = req.query.skip;

	var search = {};

	if (req.query.phone) {
		search.phone = new RegExp(req.query.phone, 'i');
	}

	Db.Employer.count(search, function(err, count) {
		if (err) {
			res.send(500, err);
			return;
		}

		Db.Employer.find(search, selectFields, {
			limit : limit,
			skip : skip
		}, function(err, employers) {
			if (err) {
				res.send(500, err);
				return;
			}

			res.send({
				count : count,
				list : employers
			});
		});
	});
});
router.get('/:id', function (req, res, next) {
	var id = req.params.id;
	Db.Employer.findById(id, selectFields, function(err, employer) {
		if (err) {
			res.send(500, err);
			return;
		}

		if (employer) {
			res.send(employer);
		} else {
			res.send(404);
		}
	});
});

/* 发送短信验证码 */
router.post('/sms', function(req, res) {
	var employer = new Db.Employer(req.body);

	var err = employer.validateSync();
	if (err) {
		res.send(500, err);
		return;
	}

	var search = req.body;
	Db.Employer.findOne(search, selectFields, function(err, resultItem) {
		if (err) {
			res.send(500, err);
			return;
		}
		var code = Math.floor(Math.random() * 1000000);
	    var time = dateFormat(new Date(), 'yyyymmddHHMMssl');
	    var sign = md5(SID + time + TOKEN);
		// 请求短信下发
		request.post({
			url: SMS_REST,
			form: {
                sid: SID,
                appId: APPID,
                sign: sign,
                time: time,
                templateId: SMS_ID,
                to: req.body.phone,
                param: code
			}
		}, function(err, response, body) {
			if (err) {
				res.send(500, err);
				return;
			}
			var smsResult = JSON.parse(body);
			console.log(smsResult);
			if (response.statusCode === 200 && smsResult.resp.respCode == '000000') {
				if (resultItem) {
					resultItem.password = code;
					resultItem.save(function(err) {
						if (err) {
							res.send(500, err);
							return;
						}

						res.send(body);
					});
				} else {
					employer.password = code;
					employer.save(function(err) {
						if (err) {
							res.send(500, err);
							return;
						}

						res.send(body);
					});
				}
			} else {
				res.send(body);
			}
		});
	});

});

/* 新增 */
router.post('/', function (req, res, next) {
	var employer = new Db.Employer(req.body);

	var err = employer.validateSync();
	if (err) {
		res.send(500, err);
		return;
	}

	employer.password = createPassword(employer.password);

	employer.save(function(err) {
		if (err) {
			res.send(500, err);
			return;
		}

		res.send(employer);
	});
});

/* 修改 不包括密码 */
router.put('/:id', function(req, res, next) {
	var id = req.params.id;
	Db.Employer.findById(id, function(err, employer) {
		if (err) {
			res.send(500, err);
			return;
		}

		if (employer) {
			delete req.body.password;

			for (var path in req.body) {
				employer.set(path, req.body[path]);
			}

			var err = employer.validateSync();
			if (err) {
				res.send(500, err);
				return;
			}

			employer.save(function(err) {
				if (err) {
					res.send(500, err);
					return;
				}

				res.send(employer);
			});
		} else {
			res.send(404);
		}
	});
});

/* 修改密码 */
router.put('/:id/password', function(req, res, next) {
	var id = req.params.id;
	Db.Employer.findById(id, function(err, employer) {
		if (err) {
			res.send(500, err);
			return;
		}

		if (employer) {
			if (employer.password != createPassword(employer.oldPassword)) {
				employer.invalidate('password', '原密码错误。', employer.oldPassword);
				var err = employer.validateSync();
				if (err) {
					res.send(400, err);
					return;
				}
			}

			employer.password = req.body.password;

			var err = employer.validateSync();
			if (err) {
				res.send(500, err);
				return;
			}

			employer.password = createPassword(employer.password);
			employer.save(function(err) {
				if (err) {
					res.send(500, err);
					return;
				}

				res.send(employer);
			});
		} else {
			res.send(404);
		}
	});
});


module.exports = router;
